import {getuserinfo} from '@/api/data'
import { Loading } from 'element-ui'
import { asyncRouterMap, constantRouterMap } from '@/router/index'

const user = {
  state: {
    userID: '',
    userInfo:'',
    routers: constantRouterMap,
    addRouters: []
  },

  mutations: {

    SET_USERINFO:(state, userInfo) => {
      state.userInfo = userInfo
    },
    SET_USERID:(state, userID) => {
      state.userID = userID
    },
    SET_ROUTERS: (state, routers) => {
      state.addRouters = routers
      state.routers = constantRouterMap.concat(routers)
    }
  },

  actions: {

    // 获取用户信息
    GetInfo({ commit, state }) {
      startLoading()
      return new Promise((resolve, reject) => {
        getuserinfo(state.userID).then(response => {
          endLoading()
          const data = response.result
          commit('SET_USERINFO', data)
          // commit('SET_USERID', data.linkdoodID);
          // setToken(state.token);
          resolve(response)
        }).catch(error => {
          endLoading()
          reject(error)
        })
      })
    },

    // 判断用户权限生成路由
    GenerateRoutes({ commit }, id) {
      return new Promise(resolve => {
        const avatar = id.toString()
        let accessedRouters
        accessedRouters = filterAsyncRouter(asyncRouterMap, avatar)
        commit('SET_ROUTERS', accessedRouters)
        resolve()
      })
    }

  }
}

let loading

function startLoading() {
  loading = Loading.service({
    lock: true,
    text: '加载中……',
    background: 'transparent'
  })
}

function endLoading() {
  loading.close()
}

/**
 * 递归过滤异步路由表，返回符合用户角色权限的路由表
 * @param asyncRouterMap
 * @param roles
 */
function filterAsyncRouter(asyncRouterMap, roles) {
  const accessedRouters = asyncRouterMap.filter(route => {
    if (hasPermission(roles, route)) {
      if (route.children && route.children.length) {
        route.children = filterAsyncRouter(route.children, roles)
      }
      return true
    }
    return false
  })
  return accessedRouters
}
function hasPermission(avatar, route) {
  if (route.meta && route.meta.avatar) {
    return route.meta.avatar.some(role => role === avatar)
  } else {
    return true
  }
}


export default user
